<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class StoreOrder extends Model
{

    protected $table = "store_order";
    use HasFactory;

    public $timestamps = false;
    protected $guarded = [];

    //关联团长
    public function head()
    {
        return $this->hasOne(StoreHead::class, 'uid', 'uid');
    }
    /**
     * 修改订单状态
     * @param $id 订单id
     * @param $status 订单状态
     * @return mixed
     * @throws \Exception
     */
    public static function updateStatus($id, $status)
    {
        $res = self::where('id', $id)->update(['status' => $status]);
        if (!$res) {
            throw new  \Exception("修改失败");
        }
        return $res;
    }
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     * 订单与订单购物车关联
     */
    public function OrderCart()
    {
        return $this->hasMany(StoreOrderCartInfo::class,'oid','id');
    }

    /**
     * @param $data //添加数据
     * @return mixed
     */
    public static function OrderAdd($data)
    {
        return DB::table('store_order')->create($data);
    }
    /**
     * @param $id
     * @param $data
     * @return mixed
     * 订单修改
     */
    public static function UpData($id,$data)
    {
        return self::where('id',$id)->update($data);
    }

    /**
     * 订单展示
     * @param $num
     * @return mixed
     */
    public static function orderPage($num)
    {
        $result = self::with('head')->orderBy('add_time', 'desc')->where('status', 1)->paginate($num);
        if (!$result) {
            throw new  \Exception("查询失败");
        }
        return $result;
    }

    /**
     * 提货
     * @param $id
     * @return string
     */
    public static function orderSend($id)
    {

        $res = StoreOrder::where(['uid' => $id, 'status' => 1])->update(['status' => 3]);
        if (!$res) {
            throw  new  \Exception('提货失败');
        }
        return $res;
    }

    /**
     * 提货
     * @param $order_id
     * @return mixed
     * @throws \Exception
     */
    public static function pickUp($order_id){
        $result=StoreOrder::where(['order_id'=>$order_id,'status'=>1])->update(['status'=>3]);
        if (!$result) {
            throw  new  \Exception('提货失败');
        }
        return $result;
    }
    /**
     * 查询商品的价格
     */
    public static function orderStatusPrice($sid)
    {
        return self::where("id",$sid)->get("total_price")->toArray();
    }
}
